package com.example.capturetheflag.connection;

import com.example.capturetheflag.helper.Singleton;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.os.AsyncTask;


public class HttpGetRequest extends AsyncTask<String, Void, Void> 
{
	private DefaultHttpClient defaultHttpClient;
	private HttpGet httpGetrequest;
	private HttpResponse httpResponse;
	private HttpEntity httpEntity;
	
		public HttpGetRequest()	
		{
			defaultHttpClient = new DefaultHttpClient();
		}

	protected int onPostExecute(Long result) {
	       return 1;
	}	
		
	@Override
	protected Void doInBackground(String... params) 
	{	
		httpGetrequest = new HttpGet(params[0]);
		httpGetrequest.setHeader("Accept", "application/json");
		httpGetrequest.setHeader("Content-type", "application/json");
		
		try
		{
		
		httpResponse = defaultHttpClient.execute(httpGetrequest);
		httpEntity = httpResponse.getEntity();
		
		 // Read response data into buffer
	      char[] buffer = new char[(int)httpEntity.getContentLength()];
	      InputStream stream = httpEntity.getContent();
	      InputStreamReader reader = new InputStreamReader(stream);
	      reader.read(buffer);
	      stream.close();
	      
	      try{
	     	JSONObject jsonObject = new JSONObject(new String(buffer));
	     	Singleton.getInstance().playersPossition = jsonObject.getJSONArray("getPlayerPointsResult");
	     	Singleton.getInstance().gameField = jsonObject;
	      }catch(Exception e){}
	      
		}
		catch (Exception e) 
		{
			// TODO: handle exception
		}
		return null;
	}
}
